// tslint:disable
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { Platform, ModalController } from '@ionic/angular';


import { StatusBar } from '@ionic-native/status-bar/ngx';


import { AppGlobalService } from 'src/app/shared/service/app-global.service';

import { HttpService } from './shared/service/http.service';
import { IndexedDBService } from "./shared/service/indexed-db.service";

import { EventService } from './shared/service/event.service';
import { NgZone } from '@angular/core';

import { ChatService } from './shared/service/chatService';
declare let $: any;
declare var wx;
declare var Totop;
declare var KeychainUUID;
declare var KeychainIDFA;
declare var BMap;
@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html'
})
export class AppComponent implements OnDestroy, OnInit {

    sessionId: string;
    appTypeCustom: any;
    constructor(

        private platform: Platform,
        private http: HttpService,
        private statusBar: StatusBar,
        public chatService: ChatService,
        private route: ActivatedRoute,
        public appGlobalService: AppGlobalService,
        public modalController: ModalController,
        private eventService: EventService,
        private indexedDBService: IndexedDBService,
        private zone: NgZone,
        // private cache: CacheService
    ) {
        // add by andrew.wen for 用户从任务栏强制强制退出app
        window['chatService'] = chatService;
        // 2024.07.23 add by andrew.wen for 用户按两下退出app 以及回调返回按钮        
        window['eventService'] = eventService;
        window['appGlobalService'] = appGlobalService;// 用于 cordova调用js 返回页面 跳转页面例如pageModal弹窗

        const bodyStyles = window.getComputedStyle(document.body);
        this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
        // this.keyboardEvent(); //android
        this.initializeApp();
        // cache.setDefaultTTL(60 * 60);
    }

    ngOnInit() {
        console.log('app init');
        // 2023年9月21日新增获取百度API
        this.getBaiduApiScript();
    }

    ngOnDestroy() {
        console.log('app destroy');
    }

    initializeApp() {
        const that = this;
        console.log('initializeApp');

        this.initlocalStorage();
        let preview = true;
        this.route.queryParams.subscribe(params => {
            // setTimeout(() => {
            //     if (localStorage.getItem("loginAccount") !== null) {
            //         if (localStorage.getItem('loginStatus') !== null) {
            //             this.appGlobalService.consoleLog('checkStateAndConnect subscribe...', '  	   ');      
            //         }
            //     }
            // }, 0);
            // 只有预览模式才取地址栏上的sessionId
            this.sessionId = params.sessionId;
            if (!this.sessionId) {
                preview = false;
            }
            if (preview) {
                localStorage.setItem('sessionId', this.sessionId);
            }

        });

        // 项目启动一定时间后重新请求一次script
        this.platform.ready().then(() => {
            // 确保不是web模拟的iOS
            // this.checkUpdate('android');
            console.log('platform.ready() 1');
            if (this.platform.is('ios') && localStorage.getItem('client') !== 'BROWSER') {

                // // ios 第一次等待网络授权
                // if (!localStorage.getItem('firstInstallIOS')) {
                //     this.eventService.eventEmit.emit('waitIOS', "1");
                // }

                // 2023年9月4日新增初始化极光推送通用方法 -> ta1
                // this.pageModalService.initJiguangPushAndAddListener();

                localStorage.setItem('platform', 'ios');
                localStorage.setItem('privacyStatement', "true");
                console.log('ios platform.ready() ');
                if ((typeof KeychainUUID) !== 'undefined') {
                    KeychainUUID.getDeviceID((id) => {
                        console.log('ready ios deviceId = ' + id);
                        this.zone.run(() => {
                            // 登录识别用
                            if (id) {
                                localStorage.setItem('imei', id);
                            } else {
                                localStorage.setItem('imei', 'unknow');
                            }
                        });
                    }, (err) => {
                        console.log('getDeviceId error:' + JSON.stringify(err));
                    });
                }

                if ((typeof KeychainIDFA) !== 'undefined') {
                    var args = {
                        'key': 'com.laijian.merchant.idfa'
                    };
                    // 激活统计用
                    KeychainIDFA.getDeviceID((id) => {
                        this.zone.run(() => {
                            localStorage.setItem('imei', id);
                            console.log('idfa:' + id);
                        });

                    }, (err) => {
                        console.log('idfa err:');
                        console.log(err);
                    }, args);
                }


                // setTimeout(() => {
                //     this.checkUpdate('ios'); // 移到tab1了
                // }, 5000);

                if ((typeof Totop) !== 'undefined') {

                    Totop.coolMethod('ToTop', success => {

                        if (success === 'ToTop') {
                            // console.log("ToTop coolMethod success :" + success);
                            this.appGlobalService.topTop = true;
                            this.eventService.eventEmit.emit('TOTOP', "TOTOP");
                        }
                    }, error => {
                        // console.log("test coolMethod error :" + error);
                    });
                }

                // if (this.statusBar !== undefined) {
                //     this.statusBar.overlaysWebView(true);
                //     this.statusBar.styleDefault();
                // }

            } else if (this.platform.is('android') && localStorage.getItem('client') !== 'BROWSER') {
                if (localStorage.getItem('privacyStatement') && localStorage.getItem('privacyStatement') === 'true') {
                    // 2023年9月4日新增初始化极光、极光一键登录推送通用方法 - > tab1
                    // this.pageModalService.initJiguangPushAndAddListener();
                }

                // if (this.statusBar !== undefined) {
                //     // this.statusBar.styleBlackTranslucent();
                //     this.statusBar.backgroundColorByHexString('#00000000');
                // }

            }
            // this.splashScreen.hide();
            console.log('ios or android ');


            // APP
            if (this.platform.is('ios') || this.platform.is('android')) {
                console.log('is APP');
                localStorage.setItem('client', 'APP');

            }

            // 浏览器
            if (this.platform.is('mobileweb')) {
                console.log('is mobileweb');
                localStorage.setItem('client', 'BROWSER');
            }
            if (!this.platform.is('mobileweb') && this.platform.is('android')) {
                localStorage.setItem('platform', 'android');
            }
            if (!this.platform.is('mobileweb') && this.platform.is('ios')) {
                localStorage.setItem('platform', 'ios');
            }
            // 小程序
            if ((typeof wx) !== 'undefined') {
                wx.miniProgram.getEnv((data) => {
                    if (data.miniprogram) {
                        // alert('miniProgram');
                        console.log('is miniProgram');
                        localStorage.setItem("client", 'JSAPI');
                        that.appGlobalService.isMiniProgram = true;
                    } else {
                        that.setStatusBar();
                    }
                });
            } else {
                that.setStatusBar();
            }


            document.addEventListener("deviceready", onDeviceReady, false);
            function onDeviceReady() {
                document.addEventListener("pause", onPause, false);
                document.addEventListener("resume", onResume, false);
                // 2023-06-28 
                if (window['MobileAccessibility'] !== undefined) {
                    window['MobileAccessibility'].usePreferredTextZoom(false);
                }
            }

            function onPause() {

                // 监听是否点击了
                if (window['appGlobalService'].isInstallBaiduMapApp === '1') { // 百度 0
                    window['appGlobalService'].isInstallBaiduMapApp = '2';
                } else if (window['appGlobalService'].isInstallTencentMapApp === '1') { // 腾讯 1
                    window['appGlobalService'].isInstallTencentMapApp = '2';
                } else if (window['appGlobalService'].isInstallGaoDeMapApp === '1') {// 高德 2
                    window['appGlobalService'].isInstallGaoDeMapApp = '2';
                }
                localStorage.removeItem('dynamicScrollTop');
                console.log('----------------  onPause');
                localStorage.setItem('backgroundPauseTime', new Date().getTime() + '');

            }

            function onResume() {
                console.log('----------------  onResume');
                that.eventService.eventEmit.emit('checkPayStatus', "1");
                window['chatService'].refreshMyFriendData();
                // 长时间放置后台重新打开app,例如10分钟后切换到前台，session过期后未刷新访问页面
                // fixed for bug-view-4617.html
                // 超过指定时间刷新页面。
                // 设置刷新tab
                setTimeout(() => {
                    if (localStorage.getItem("loginAccount") !== null) {
                        if (localStorage.getItem('loginStatus') !== null) {
                            that.appGlobalService.consoleLog('系统：初始化状态然后重新建立连接', '  	   ');
                            that.chatService.reconnectAttempts = 0;
                            that.chatService.reconnect(true);
                        } else {
                            that.appGlobalService.consoleLog('系统：登录状态异常！', '  	   ');
                        }
                    }else{
                        that.appGlobalService.consoleLog('系统：登录账号异常！', '  	   ');
                    }
                }, 0);
                const onResumeTime = new Date().getTime();
                if (localStorage.getItem('backgroundPauseTime')) {
                    // tslint:disable-next-line:radix
                    const t2 = parseInt(localStorage.getItem('backgroundPauseTime'));
                    const disparity = onResumeTime - t2;
                    const min = Math.round(disparity / 1000);
                    console.log('compare min：' + min);
                    if (min >= 600) {
                        localStorage.setItem('needRefresh', 'true');
                        localStorage.setItem('needRefreshTab1', 'true');
                        localStorage.setItem('needRefreshTab2', 'true');
                        localStorage.setItem('needRefreshTab3', 'true');
                        localStorage.setItem('needRefreshTab4', 'true');
                        localStorage.setItem('needRefreshTab5', 'true');
                    }
                }
            }
        });
    }

    setStatusBar() {
        if (localStorage.getItem('platform') == 'android') {
            if (this.statusBar !== undefined) {
                // this.statusBar.styleBlackTranslucent();
                this.statusBar.backgroundColorByHexString('#00000000');
            }
        }
        if (localStorage.getItem('platform') == 'ios') {
            if (this.statusBar !== undefined) {
                this.statusBar.overlaysWebView(true);
                this.statusBar.styleDefault();
            }
        }
    }
    initlocalStorage() {
        let that = this;
        localStorage.removeItem('ShareH5');

        localStorage.removeItem('appNav');
        localStorage.removeItem('netState');
        localStorage.removeItem('reGetSession');
        // localStorage.removeItem('targetObj');
        localStorage.removeItem('needRefresh');
        localStorage.removeItem('needRefreshTab1');
        localStorage.removeItem('needRefreshTab2');
        localStorage.removeItem('needRefreshTab3');
        localStorage.removeItem('needRefreshTab4');
        localStorage.removeItem('needRefreshTab5');
        localStorage.removeItem('searchParams');
        localStorage.removeItem('lastNavIndex');
        localStorage.removeItem('useTarget');
        localStorage.removeItem('fromPostOrEdit');
        localStorage.removeItem('tempPoint');
        localStorage.removeItem('askForTag');
        localStorage.removeItem('needRefresh-2');
        localStorage.removeItem('sendedSessionId');
        // localStorage.removeItem('connUserId');
        // localStorage.removeItem('loginStatus');
        localStorage.removeItem('loginParams');
        localStorage.removeItem('WebSocketSID');
        // localStorage.removeItem('userId');
        localStorage.removeItem('isDetailPage');
        localStorage.removeItem('invitationArr');
        localStorage.removeItem('inMsgNum');
        localStorage.removeItem('isEnterDetailChatPage');
        localStorage.removeItem('chatPageFrom');

        localStorage.removeItem('shareOppDetail');
        localStorage.removeItem('needRemberResult');
        localStorage.removeItem('refreshbtNavDefaultTabForPxwTag');
        localStorage.removeItem('startRefreshTimerTag');
        localStorage.removeItem('clearAchieveInfoTimerTag');
        localStorage.removeItem('dynamicScrollTop');
        localStorage.removeItem('backToNewShop');
        localStorage.removeItem('currentPageIsDetailPage');
        localStorage.removeItem('backgroundPauseTime');
        localStorage.removeItem('privacyStatement');
        localStorage.removeItem("titleBarBackCount");
        localStorage.removeItem('myrealEstatequickWay');
        localStorage.removeItem('myrealEstateresetAssured');
        localStorage.removeItem('myrealEstateOppId');
        localStorage.removeItem('quote_way');

        // 蜂喔商户1.6.18 版本问题
        localStorage.removeItem('refreshThenBack');
        // 1.6.34 新增标志位
        if (!localStorage.getItem('clearTableDataTag')) {
            setTimeout(() => {
                that.indexedDBService.clearTableData('chat', (result) => {
                    // console.log('clearChatTableResult', result);
                });
            }, 500);
            localStorage.setItem('clearTableDataTag', '1');
        }

    }


    getBaiduApiScript() {
        $.get(this.http.baiduAPI, (data, status) => {
            if (data) {
                const beginIndex = data.indexOf('src="') + 5;
                const endIndex = data.indexOf('"></script>');
                const realSubjectUrl = data.substring(beginIndex, endIndex);
                console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	   ', realSubjectUrl);
                const newScript = document.createElement('script');
                newScript.setAttribute('src', decodeURIComponent(realSubjectUrl));
                newScript.onload = () => {
                    // 成功了在加载 infoBox.js
                    const infoBoxScript = document.createElement('script');
                    const subjectUrl2 = 'assets/infoBox_min.js';
                    infoBoxScript.setAttribute('src', subjectUrl2);
                    infoBoxScript.onload = () => {
                        // console.log(new Date().toLocaleString() + '.'
                        //     + new Date().getMilliseconds()
                        //     + '  	   infoBoxScript load success!',
                        //     '  infoBoxScript load success!	   ');
                    };
                    document.getElementsByTagName('head')[0].appendChild(infoBoxScript);
                };
                document.getElementsByTagName('head')[0].appendChild(newScript);
            }
        });

        // 2024.01.11如果服务器异常，则使用
        setTimeout(() => {
            if (typeof (BMap) === 'undefined') {
                const newScript = document.createElement('script');
                newScript.setAttribute('src', '/assets/js/baiduapi.js');
                newScript.onload = () => {
                    console.log('', 'load success!');
                };
                document.getElementsByTagName('head')[0].appendChild(newScript);
            }
        }, 3000);
    }
}
